package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired // 用于查询库存
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
		// 先转化context
		CreateOrderContext orderContext = (CreateOrderContext) context;
		List<CartProductDto> dtoList = orderContext.getCartProductDtoList();
		List<Long> productIds = orderContext.getBuyProductIds();

		if (CollectionUtils.isEmpty(productIds)){
			// lamda表达式进行实现 -- 代替for循环实现
			// for (CartProductDto cartProductDto : dtoList) {
			// 	productIds.add(cartProductDto.getProductId());
			// }
			productIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
		}
		// 根据大小进行排序
		productIds.sort(Long::compareTo);

		// 扣减库存之前 -- 进行库存锁定
		List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);
		// 假如库存为空
		if (CollectionUtils.isEmpty(stockList)){
			throw new BizException("库存未初始化！！！");
		}
		// 如果productIds中的数据条数不等于stockList的条数
		if (productIds.size() != stockList.size()){
			throw new BizException("有些商品库存还未初始化！！！");
		}
		// 库存不为空 -- 扣减库存
		for (CartProductDto cartProductDto : dtoList) {
			Long productId = cartProductDto.getProductId();
			Long productNum = cartProductDto.getProductNum();
			// TODO productNum存在限购数量，不可超过

			Stock stock = new Stock();
			stock.setItemId(productId);
			stock.setLockCount(productNum.intValue());
			stock.setStockCount(-productNum);

			stockMapper.updateStock(stock);
		}
		return true;
	}
}
